//
//  ARPostViewController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/10.
//

import UIKit
import SnapKit

class ARIndexPostViewController: ARBaseViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.ar_setupNavBgImg()
        
        self.setupUI()
    }
    
    // MARK: - UI
    
    private func setupUI() {
        self.addChild(editViewController)
        self.view.addSubview(editViewController.view)
        self.view.addSubview(postBtn)
        
        editViewController.view.snp.makeConstraints { make in
            make.top.right.left.equalToSuperview()
            // Adaptive height
        }
        
        postBtn.snp.makeConstraints { make in
            make.width.equalTo(157)
            make.height.equalTo(38)
            make.centerX.equalToSuperview()
            make.top.equalTo(editViewController.view.snp.bottom).offset(68)
        }
        
        // 白色的返回
        self.ar_configWhiteBackItem()
        
        self.updatePostBtnEnable()
    }
    
    // MARK: - Action
    
    @objc private func postBtnClicked(_ sender: UIButton) {
        guard let work = editViewController.createWork() else {
            return
        }
        self.ar.showLoading()
        /// 发布地点
        ARDataCenter.default.postRecommendation(work) { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            
            // 成功
            let vc = ARRecommendationPostReviewAlert()
            vc.dismissCallback = {
                self?.ar_transitionToBack()
            }
            self?.present(vc, animated: true)
        }
    }
    
    private func updatePostBtnEnable() {
        postBtn.isEnabled = editViewController.judgeWorkCanPost()
    }

    // MARK: - Lazy
    
    private lazy var editViewController: ARPostEditController = {
        let vc = ARPostEditController()
        vc.contentDidChangeCallback = { [weak self] in
            self?.updatePostBtnEnable()
        }
        return vc
    }()
    
    private lazy var postBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(postBtnClicked(_:)), for: .touchUpInside)
        btn.setBackgroundImage(.init(named: "index_post_btn_bg"), for: .normal)
        btn.titleLabel?.font = ARHelper.font(16, weight: .medium)
        btn.setTitle(ARHelper.localString("Apply to add"), for: .normal)
        return btn
    }()

}
